<html class="x-admin-sm" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/css/font.css">
    <link rel="stylesheet" href="/static/css/xadmin.css">
    <script src="/static/lib/layui/layui.js" charset="utf-8"></script>
    <script src="/static/js/iconPicker.js"></script>
    <script type="text/javascript" src="/static/js/xadmin.js"></script>
    <script src="/static/js/axios.min.js"></script>
</head>

<body>
<div class="x-nav">
    <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a><cite>添加商品</cite></a>
    </span>
</div>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-card">
            <form name="addProduct" class="layui-form layui-form-pane" action="">
                <div class="layui-card-header">基本信息</div>
                <div class="layui-card-body ">
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品标题</label>
                        <div class="layui-input-block">
                            <input type="text" name="productTitle" autocomplete="off" placeholder="请输入商品标题"
                                   class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">商品价格</label>
                        <div class="layui-input-block">
                            <input type="number" name="price" autocomplete="off" placeholder="请输入商品价格"
                                   class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">商品关键词</label>
                        <div class="layui-input-block">
                            <input type="text" name="keywords" autocomplete="off" placeholder="请输入商品关键词 关键词用英文分号 ; 分割"
                                   class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">所属分类</label>
                        <div class="layui-input-inline">
                            <select id="cateSelect" name="cid">
                                <option value="-1">请选择分类</option>
                            </select>
                        </div>
                    </div>

                    <div class="layui-form-item" pane="">
                        <label class="layui-form-label">立刻上架</label>
                        <div class="layui-input-block">
                            <input type="checkbox" checked name="status" lay-skin="switch" lay-filter="switchTest"
                                   title="开关">
                        </div>
                    </div>
                </div>

                <div class="layui-card-header">商品图片</div>
                <!-- todo 优化图片选择样式-->
                <div class="layui-card-body ">
                    <div class="layui-form-item" pane="">
                        <label class="layui-form-label">图片空间</label>
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn"
                                    onclick="xadmin.open('上传图片','/admin/image_zone/image_upload',800,600)">
                                上传
                            </button>
                        </div>
                    </div>

                    <div class="layui-form-item layui-inline" pane="">
                        <label class="layui-form-label">主图</label>
                        <div class="layui-input-inline" style="display:flex;">
                            <img id="mainImage" src="" alt="" style="height: 100px;width: 100px;visibility: hidden">
                            <button type="button" class="layui-btn" id="imagePicker" lay-filter="imagePicker">
                                选择
                            </button>
                            <input type="hidden" name="mainImage">
                        </div>
                    </div>

                    <div class="layui-form-item" pane="">
                        <label class="layui-form-label">副图</label>
                        <div class="layui-input-block" id="secondaryImage" style="display:flex;">
                            <button type="button" id="imagePicker1" lay-filter="imagePicker"
                                    class="layui-btn">选择
                            </button>
                        </div>
                    </div>
                </div>

                <div class="layui-card-header">商品SKU</div>
                <div class="layui-card-body ">
                    <table class="layui-table" id="skuTable" lay-filter="skuTable"></table>
                    <button type="button" class="layui-btn layui-btn-sm" data-type="reload"
                            onclick="addSkuTableRow()"
                            lay-event="addFunctionModule">新增行
                    </button>
                </div>

                <div class="layui-card-header">商品介绍</div>
                <div class="layui-card-body ">
                    <div class="layui-form-item layui-form-text">
                        <label for="desc"></label><textarea id="desc" name="desc" style="display: none;"></textarea>
                    </div>
                </div>

                <div class="layui-form-item">
                    <button type="button" class="layui-btn" onclick="postForm()">提交</button>
                </div>
            </form>

        </div>
    </div>
</div>
</body>

<script>
    layui.use('form');
    layui.config({
        base: '/static/js/'
    }).extend({
        tableSelect: 'tableSelect'
    });
    layui.use('tableSelect', function () {
        let tableSelect = layui.tableSelect;
        tableSelect.render({
            elem: '#imagePicker',	//定义输入框input对象 必填
            checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
            searchKey: 'keyword',	//搜索输入框的name值 默认keyword
            searchPlaceholder: '图片描述搜索',	//搜索输入框的提示文字 默认关键词搜索
            table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                url: '/index.php/admin/imageZone/getImageList',
                height: 500,
                cols: [[
                    {type: 'radio', title: '选择', align: 'center'},
                    {field: 'img_url', title: '图片', templet: '#slot_image', align: 'center'},
                    {field: 'img_comment', title: '图片描述'},
                    {field: 'add_time', title: '添加时间', align: 'center'}
                ]]
            },
            done: function (elem, data) {
                if (data) {
                    let mainImage = $('#mainImage')[0]
                    let src = data.data[0].img_url
                    let mainImageInput = document.addProduct.mainImage;

                    mainImage.src = src
                    mainImage.style.visibility = 'visible'
                    mainImageInput.value = data.data[0].img_url
                }
                //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
                //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
            }
        })
    })
    layui.use('tableSelect', function () {
        let tableSelect = layui.tableSelect;
        tableSelect.render({
            elem: '#imagePicker1',	//定义输入框input对象 必填
            checkedKey: 'id', //表格的唯一建值，非常重要，影响到选中状态 必填
            searchKey: 'keyword',	//搜索输入框的name值 默认keyword
            searchPlaceholder: '图片描述搜索',	//搜索输入框的提示文字 默认关键词搜索
            table: {	//定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
                url: '/index.php/admin/imageZone/getImageList',
                height: 500,
                cols: [[
                    {type: 'checkbox', title: '选择', align: 'center'},
                    {field: 'img_url', title: '图片', templet: '#slot_image', align: 'center'},
                    {field: 'img_comment', title: '图片描述'},
                    {field: 'add_time', title: '添加时间', align: 'center'}
                ]]
            },
            done: function (elem, data) {
                if (data) {
                    let temp = data.data;
                    if (temp.length > 4) {
                        layer.msg('副图最多四张', {icon: 2, time: 1500});
                        return
                    }
                    let imageContainer = $('#secondaryImage')[0]

                    for (let i = 0; i < temp.length; ++i) {

                        let img = new Image()
                        img.src = temp[i].img_url
                        img.style.width = '100px'
                        img.style.height = '100px'
                        img.onload = () => {
                            imageContainer.append(img)
                        }

                        let input = document.createElement("input");
                        input.type = 'hidden';
                        input.name = 'iamge' + i;
                        input.value = img.src;
                        imageContainer.append(input);
                    }
                }
                //选择完后的回调，包含2个返回值 elem:返回之前input对象；data:表格返回的选中的数据 []
                //拿到data[]后 就按照业务需求做想做的事情啦~比如加个隐藏域放ID...
            }
        })
    })
    layui.use('layedit', function () {
        let layedit = layui.layedit;
        layedit.set({
            uploadImage: {
                url: '/index.php/admin/ImageZone/uploadImage' //接口url
            }
        });
        layedit.build('desc'); //建立编辑器
    })
    layui.use(['form', 'upload', 'layer'], function () {
        $.ajax({
            url: '/admin/product/getCatesList',
            type: 'get',
            success: function (data) {
                $.each(data.data, function (index, value) {
                    $('#cateSelect').append(new Option(value.title, value.id));
                });
                layui.form.render("select");
            }
        })
    })
    layui.use('table', function () {
        let table = layui.table;
        table.render({
            elem: '#skuTable'
            // ,url:'/demo/table/user/'
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , cols: [[
                {field: 'sku_title', title: 'SKU标题', minWidth: 150, edit: 'text'}
                , {field: 'sku_price', width: '25%', title: '价格', edit: 'number'}
                , {field: 'sku_count', title: '库存', width: '25%', edit: 'text'}
            ]]
            , data: [{sku_title: '', sku_price: '', sku_count: ''}]
        });
    })


    /**
     * 新增行
     */
    addSkuTableRow = function () {
        let dataBak = []   //定义一个空数组,用来存储之前编辑过的数据已经存放新数据
        let tableBak = layui.table.cache.skuTable
        for (let i = 0; i < tableBak.length; i++) {
            //将之前的数组备份
            dataBak.push({
                'sku_title': tableBak[i].sku_title,
                'sku_price': tableBak[i].sku_price,
                'sku_count': tableBak[i].sku_count
            })
        }

        // 新增空白行
        dataBak.push({"sku_title": "", "sku_price": "", "sku_count": ""})

        // 将新数据重新载入表格
        layui.table.reload("skuTable", {data: dataBak})
    }

    /**
     * 获取列表数据
     */
    function getDataList(tableId) {
        let table = layui.table
        let tableData = table.cache[tableId]
        let resData = []
        if (tableData) {
            for (const row of tableData) {
                console.log(row)
                if (!row.sku_title || !row.sku_price || !row.sku_count) continue
                resData.push({
                    sku_title: row.sku_title, sku_price: row.sku_price, sku_count: row.sku_count
                })
            }
            return resData
        }
        return []
    }

    function encodeURI(data) {
        let ret = ''
        for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
    }

    //todo 表单前端校验
    function postForm() {
        layer.confirm('确认上传吗？', function () {
            let imageInputs = $('#secondaryImage>input')
            let res = []
            for (const item of imageInputs) {
                res.push(item.value)
            }
            let skuData = (getDataList('skuTable'))

            axios({
                url: '/index.php/admin/Product/addProduct',
                method: 'post',
                headers: {
                    'Content-Type': 'application/json'
                },
                params: {},
                // transformRequest: [function (data) {
                //     return encodeURI(data)
                // }],
                data: {
                    title: document.addProduct.productTitle.value,
                    cid: document.addProduct.cid.value,
                    keywords: document.addProduct.keywords.value,
                    mainImage: document.addProduct.mainImage.value,
                    secondaryImage: res,
                    price: document.addProduct.price.value,
                    desc: document.addProduct.desc.value,
                    status: document.addProduct.status.value,
                    skuData: skuData
                },
                // withCredentials: true
            })
        })
    }
</script>

<!--嵌入组件内的自定义模板-->
<script type="text/html" id="slot_image">
    <img src="{{d.img_url}}" alt="{{d.img_url}}" style="height: 100px; width: auto;object-fit: contain"/>
</script>
<script type="text/html" id="slot_skuTitle">
    <input type="text" class="sku-text-input" name="{{d.sku_title}}" placeholder="请输入SKU标题">
</script>
<script type="text/html" id="slot_skuPrice">
    <input type="number" class="sku-text-input" placeholder="请输入SKU价格">
</script>
<script type="text/html" id="slot_skuCount">
    <input type="number" class="sku-text-input" placeholder="请输入SKU库存数">
</script>

<style>
    .layui-table-cell {
        height: 100%;
        line-height: 100%;
        padding: 10px 5px;
    }

    .layui-table-view .layui-form-radio {
        height: 20px;
        line-height: 20px;
    }

    .sku-text-input {
        width: 100%;
        height: 30px;
        border: none;
        padding: 0 10px;
    }
</style>
</html>
